package cn.js.sangu.unitStore.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.core.JsonProcessingException;

import cn.hutool.core.util.StrUtil;
import cn.js.sangu.unitStore.common.LogType;
import cn.js.sangu.unitStore.common.MyLogsAOP;
import cn.js.sangu.unitStore.common.R;
import cn.js.sangu.unitStore.dto.PartAttributeDTO;
import cn.js.sangu.unitStore.service.AutoCodeService;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RequestMapping("autocode")
@RestController
public class AutoCodeController {

    static final String OPERATION_AUTOCODE = "自动编码";

    @Autowired
    AutoCodeService autoCodeService;

    @MyLogsAOP(operation = OPERATION_AUTOCODE, operaType = LogType.AUTO_CODE)
    @RequestMapping("autocode")
    public R autocode(@RequestBody PartAttributeDTO dto) throws JsonProcessingException {
        if (dto == null) {
            throw new IllegalArgumentException("ExcelData对象不能为null");
        }
        if (StrUtil.isBlank(dto.getTuhao()) || StrUtil.isBlank(dto.getName()) ||
                StrUtil.isBlank(dto.getLeibie())) {
            throw new IllegalArgumentException("图号、名称、类别字段都不能为空");
        }
        return R.ok(autoCodeService.autocode(dto));
    }

    @MyLogsAOP(operation = OPERATION_AUTOCODE, operaType = LogType.PARSE_ATTRIBUTES)
    @PostMapping("parseAttributes")
    public R parseAttributes(@RequestBody String code) throws JsonProcessingException {
        // 验证编码不为空
        if (code == null || code.trim().isEmpty()) {
            return R.fail("编码不能为空");
        }

        // 验证编码格式（示例：14位长度）
        if (code.length() != 14) {
            return R.fail("编码格式不正确，必须为14位");
        }
        PartAttributeDTO attributes = autoCodeService.parseAttributes(code);
        return R.ok(attributes);
    }

    @MyLogsAOP(operation = OPERATION_AUTOCODE, operaType = LogType.CLEAR_COUNT)
    @GetMapping("clearCount")
    public R clearCount() {
        autoCodeService.clearCount();
        return R.ok("成功连接服务并清除缓存");
    }
}
